package ar.uba.fi.taller2.jh.BStree;

import java.util.*;
import ar.uba.fi.taller2.jh.BPBasicTree.*;
import ar.uba.fi.taller2.jh.Tree.*;

/*****************************************************************************
 * @author Sebastian rivas
 * @version 1.0
 * 
 ****************************************************************************/

public class BSLeafNode extends BPBasicLeafNode {

  /****************************************************************************
   * CONSTRUCTOR
   *
   * @param comp Comparator
   * @param n_recs int
   ***************************************************************************/

  public BSLeafNode(Comparator comp,int n_recs, boolean _isRoot, Tree _tree) {
	  super(comp,n_recs, _isRoot, _tree);
  }

  /****************************************************************************
   * CONSTRUCTOR
   *
   * @param o BSLeafNode
   ***************************************************************************/

  public BSLeafNode(BSLeafNode o) {
	  super(o);
  }

  public int minSize() {
		  return (int)Math.floor(getNum_records()/2);
  }
  
  public Node splitAt(int pos) {

	  int newSize = this.size()-pos;
	  boolean newRoot = newSize>this.num_records;
	  
	  BSLeafNode newNode = new BSLeafNode(comparator,this.num_records, newRoot, this.tree);
	  for(int i=pos; i<this.size(); i++) {
		   newNode.copyRecord(i-pos, this.records[i]);
	  }
	  newNode.rsize = newSize;
	  this.rsize = pos;

	  if(this.isRoot) {
		  this.id = this.tree.getNextNodeId();
		  this.tree.getDisk().storeBlock(this.id.toString());
	  }
	  
	  this.isRoot = false;
	  
	  return newNode;
  }
  
public int getNum_records() {
	return this.isRoot? num_records*2 : num_records;
}

public Node makeRoot() {
	
	BSLeafNode auxNode = new BSLeafNode(comparator, this.num_records, true, this.tree);
	for(int i=0; i<this.size(); i++) {
		auxNode.append(this.records[i], null);
	}
	this.tree.getDisk().releaseBlock(this.id);
	return auxNode;
}
}